<?php

/**
 * shortcut to create url
 * 
 * @param mixed $route
 * @param mixed $params
 * @param mixed $ampersand
 */
function url($route, $params = array(), $ampersand = '&')
{
    return Yii::app()->controller->createUrl($route, $params, $ampersand);
}

/**
 * site base url
 */
function baseUrl()
{
    return Yii::app()->request->getBaseUrl(true);
}

/**
 * theme base url
 */
function themeUrl()
{
    if (Yii::app()->theme)
        return Yii::app()->theme->baseUrl;
    else
        return Yii::app()->baseUrl;
}

/**
 * Application base path
 */
function basePath()
{
    return Yii::app()->basePath;
}

/**
 * Application runtime path
 */
function runtimePath()
{
    return Yii::app()->basePath . '/runtime';
}

/**
 * Application cache path
 */
function cachePath()
{
    return Yii::app()->basePath . '/runtime/cache';
}

/**
 * Application clientScript object
 * @return CClientScript
 */
function cs()
{
    return Yii::app()->clientScript;
}

/**
 * @return CHttpRequest
 */
function request()
{
    return Yii::app()->request;
}

/**
 * current logged in user
 * @return CWebUser
 */
function user()
{
    return Yii::app()->user;
}

/**
 * @return CController
 */
function controller()
{
    return Yii::app()->controller;
}

/**
 * Convert unix timestamp to time
 * @param $intTime
 * @return string
 */
function convertIntToTime($intTime)
{
    return intval($intTime / 60) . ":" . str_pad(($intTime % 60), 2, "0", STR_PAD_LEFT);
}

/**
 * @param $imagePath
 * @param $width
 * @param $height
 * @return string
 */
function imageCrop1($imagePath, $width, $height)
{
    if (trim($imagePath) == '')
    {
        $imagePath = 'files/no-image.png';
    }
    if (!file_exists($imagePath))
        return '';
    return baseUrl() . "/image.php?thumb=" . FlexImage::createThumbFilename($imagePath, intval($width), intval($height));
}

/**
 * Convert zip code to lat and long
 * Code example:
 * $val = getLnt('90001');
 * echo "Latitude: ".$val['lat']."<br>";
 * echo "Longitude: ".$val['lng']."<br>";
 * @param $zip
 * @return mixed
 * @author thuann89@gmail.com
 */
function getLnt($address)
{
    $formatted     = "{$address}";
    $url           = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($formatted) . "&sensor=false";
    $result_string = file_get_contents($url);
    $result        = json_decode($result_string, true);
    if (isset($result['results'][0]))
    {
//        $result1[]=$result['results'][0];
//        $result2[]=$result1[0]['geometry'];
//        $result3[]=$result2[0]['location'];
        return $result['results'][0]['geometry']['location'];
    }
    return null;
}
